<script setup lang="ts">
import { ref } from "vue";
import navbar from "@/components/navbar/navbar.vue";
import goodsWaterfallIndex from "@/components/goods/goodsWaterfallIndex.vue";
import { jump, router, toast } from "@/utils/tools";
import { onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { onReachBottom } from "@dcloudio/uni-app";
import updateApp from "@/utils/updateApp";
import { onLoad, onPageScroll } from "@dcloudio/uni-app";
import { apiLogin } from "@/apis/login";
import { getToken, login, setToken, wxLogin } from "@/utils/auth";
import cache from "@/utils/cache";
import { onShow } from "@dcloudio/uni-app";
import { apiSlideList } from "@/apis";
import { apiProductPage, typesInfo } from "@/apis/product";
import { computed } from "vue";
import { reactive } from "vue";
import { onLaunch } from "@dcloudio/uni-app";
import { onPullDownRefresh } from "@dcloudio/uni-app";
import { useUserStore } from "@/stores/user";
import { apiGetUserInfo, noReadNum, activities } from "@/apis/user";
import { apiPreferential, apiReceive, apiNoReceive } from "@/apis/index";
import { onReady } from "@dcloudio/uni-app";
import homeBg from "@/static/images/home-bg.png";

const userStore = useUserStore();
const searchParams = ref("");
const oldleftList: any = ref([]);
const oldrightList: any = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const pageList = ref([]);
const leftList: any = ref([]);
const rightLists: any = ref([]);
const userinfo = reactive({});
const orderField = ref("default");
const orderType = ref("desc");
const types = ref(null);
const tag1 = ref(true);
const tag2 = ref(true);
const tag3 = ref(true);
const isMore = ref(false);
const cityProvinceStr = ref("北京市朝阳区");
const noReadNumTip = ref(0);
const scrollTop = ref(0);
let appUser = ref({});
const userSelectList = reactive([
  {
    name: "价格",
    type: "price",
    id: 0,
  },
  {
    name: "认证",
    type: "approve",
    id: 1,
  },
  {
    name: "最新",
    type: "ratePrice",
    id: 2,
  },
  {
    name: "筛选",
    type: "filters",
    id: 3,
  },
]);
const userSelectListInd = ref(0);
const columns = reactive([
  [
    {
      label: "雪月夜",
      // 其他属性值
      id: 2021,
      // ...
    },
    {
      label: "冷夜雨",
      id: 804,
    },
  ],
]);
const picker = ref();
const handleLogin = () => {
  // uni.showToast({
  //   title: '请登录~',
  //   icon: 'none',
  //   success: () => {
  //     setTimeout(() => {
  jump({
    url: "/pages/login/login",
  });
  // }
  // })
};
const navbarFixed = ref(false);
const placeholder = ref("请输入您想要搜索的奇石/店铺");
const slideSwiper = ref([]);
//首页弹窗
const indexPopup = ref();
//优惠券数据
let disccountCounpon = ref([]);
//显示优惠券索引
let counponIndex = ref(0);
// 监听页面滚动
onPageScroll((e: any) => {
  scrollTop.value = e.scrollTop;
});
// 打开分享
onShareAppMessage((e: any) => {
  //console.log("----分享----", e);
  return {
    title: "",
    path: `/pages/index/index?inviterId=${userStore.userInfo.id}`,
  };
});
//分享到朋友圈
onShareTimeline((e: any) => {
  //console.log("----分享到朋友圈----", e);
  return {
    title: "",
    query: `inviterId=${userStore.userInfo.id}`,
    path: `/pages/index/index?inviterId=${userStore.userInfo.id}`,
  };
});
const getProductPage = async (e: any = {}) => {
  let appUserId = null;
  if (userStore.userInfo === undefined) {
    appUserId = null;
  } else {
    appUserId = userStore.userInfo.id;
  }
  if (e.screen) {
    leftList.value = [];
    rightLists.value = [];
  }

  let res = await apiProductPage({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    orderField: orderField.value,
    orderType: orderType.value,
    types: types.value,
    appUserId: appUserId,
    // shopName: searchParams.value
  });
  // let oldList = res.rows.map((item:any)=>{
  //   item.images = item?.images.split(",")
  //   item.videos = item?.videos.split(",")
  //   return  item
  // });
  // console.log(oldList, 'oldListoldList----')
  // leftList.value = [...leftList.value, ...oldList]
  // rightLists.value = [...rightLists.value, ...oldList]
  // isMore.value = leftList.value.length < res.total
  // console.log(res.rows,'----apiProductPage')
  // if (res.rows.length < 10) {
  //   console.log(22222222222);
  //   isMore.value = true;
  //   return false;
  // }
  // 停止当前下拉
  // uni.stopPullDownRefresh();
  // pageList.value = res.rows;
  const total = res.total;
  handlePageList(res.rows, total);
};
const handlePageList = (data: any, total: any) => {
  for (let i = 0; i < data.length; i++) {
    // data[i].images = (data[i].images || data[i].videos).split(",");
    if (data[i]?.images) {
      data[i].images = data[i]?.images.split(",");
    }
    if (data[i]?.videos) {
      data[i].videos = data[i]?.videos.split(",");
    }
    if (i % 2 === 0) {
      // leftList.value.push(data[i]);
      oldleftList.value.push(data[i]);
    } else {
      // rightLists.value.push(data[i]);
      oldrightList.value.push(data[i]);
    }
  }
  let newarrleft = [...leftList.value, ...oldleftList.value];
  let newrightList = [...rightLists.value, ...oldrightList.value];
  const uniqueLeft = [...new Set(newarrleft.map(JSON.stringify))].map(
    JSON.parse
  );
  const uniqueRight = [...new Set(newrightList.map(JSON.stringify))].map(
    JSON.parse
  );
  leftList.value = uniqueLeft;
  rightLists.value = uniqueRight;
  isMore.value = leftList.value.length + rightLists.value.length < total;
};
// 触底下拉下一页
onReachBottom((e: any) => {
  //console.log("触底触底触底------");
  // if (isMore.value) return;
  // if (leftList.value.length >= 5) {
  //   console.log("--触底了---", e);
  //   pageNum.value++;
  //   getProductPage();
  // }
  if (isMore.value) {
    pageNum.value++;
    getProductPage();
  }
});

// 监听用户下拉刷新
onPullDownRefresh(() => {
  // isMore.value = false;
  // pageNum.value = 1;
  // let data = {
  //   screen: true,
  // };
  // getProductPage(data);
});
const handleCollect = () => {
  jump({ url: "/pagesIndex/collect/index", method: "navigateTo" });
};
const handleMarket = (e: any) => {
  jump({ url: `/pagesIndex/market/index?&title=${e}`, method: "navigateTo" });
};
const handleJewellery = (e: any) => {
  jump({ url: `/pagesIndex/jewellery/jewellery?&title=${e}`, method: "navigateTo" });
};
// 接收分享的参数
onLoad((options: any) => {
  //console.log(options, "options-接收分享的参数");
  //console.log(getCurrentPages()[0], "getCurrentPages");
  let optionsId = getCurrentPages()[0].options;
  //console.log(optionsId, "optionsId");
  uni.setStorageSync("inviterId", optionsId?.inviterId);
  uni.setStorageSync("shareDetailId", optionsId?.shareDetailId);
  uni.setStorageSync("shareTitle", optionsId?.shareTitle);
  // inviterIdValue.value = options.inviterId
  // wx.getShareInfo({
  //     shareTicket: opt.shareTicket,
  //     success:(res:any)=>{
  //        console.log(res, 'getShareInfo')
  //     }
  // })
  oldleftList.value = [];
  oldrightList.value = [];
  leftList.value = [];
  rightLists.value = [];
  pageNum.value = 1;
  isMore.value = false;
  pageSize.value = 10;
  getProductPage();
});

onShow(async () => {
  getSlideList();
  // getUserInfo();
  // getNoReadNum();
  getTypesInfo();
  getActivities();
  cityProvinceStr.value = cache.get("cityProvince");

  if (userStore.state.isLogin) {
    //优惠券
    getPreferential();
  }
});
//优惠券
const getPreferential = async () => {
  let res = await apiPreferential();
  //console.log("优惠券", res);
  if (res.code == 200 && res.data && res.data !== "null") {
    disccountCounpon.value = res.data;
    //console.log("优惠券", disccountCounpon.value);
    setTimeout(() => {
      indexPopup.value.open();
    }, 500);
  }
};
//关闭优惠券弹窗
const closePop = () => {
  indexPopup.value.close();
  getNoReceive();
  if (disccountCounpon.value.length - 1 > counponIndex.value) {
    counponIndex.value++;
    setTimeout(() => {
      indexPopup.value.open();
    }, 500);
  }
};

//立即领取
const receiveClick = async () => {
  let data = {
    couponId: disccountCounpon.value[counponIndex.value].couponId,
  };
  let res = await apiReceive(data);
  //console.log("领取优惠券", res);
  uni.showToast({
    icon: "none",
    title: res.msg,
  });
  indexPopup.value.close();
  if (disccountCounpon.value.length - 1 > counponIndex.value) {
    counponIndex.value++;
    setTimeout(() => {
      indexPopup.value.open();
    }, 500);
  }
};
//不领取优惠券
const getNoReceive = async () => {
  let data = {
    couponId: disccountCounpon.value[counponIndex.value].couponId,
  };
  let res = await apiNoReceive(data);
  //console.log("不领取优惠券", res);
};

const getSlideList = async () => {
  let res = await apiSlideList();
  slideSwiper.value = res.data;
};

const getUserInfo = async () => {
  let res = await apiGetUserInfo();
  Object.assign(userinfo, res.data);
};

const getNoReadNum = async () => {
  let res = await noReadNum();
  noReadNumTip.value = res.data;
};
const activitiesImage = ref("");
const activitiesId = ref();
const getActivities = async () => {
  let res = await activities();
  //console.log(res, "评选活动入口");
  if (res.code === 200) {
    activitiesImage.value = res.data.images;
    activitiesId.value = res.data.id;
  }
};
const getTypesInfo = async () => {
  let res = await typesInfo();
  columns[0] = res.data;
};
const confirm = (e: any) => {
  //console.log("confirm", e);
  let data = {
    screen: true,
  };
  types.value = e.value[0].typeId;
  leftList.value = [];
  rightLists.value = [];
  oldleftList.value = [];
  oldrightList.value = [];
  pageNum.value = 1;
  pageSize.value = 10;
  isMore.value = false;
  getProductPage(data);
};
onReady(() => { });
const handleScreen = (item: any, index: any) => {
  //console.log(item, index);
  userSelectListInd.value = index;
  orderField.value = item.type == "filters" ? "default" : item.type;
  let data = {
    screen: true,
  };
  if (item.type == "price") {
    tag1.value = !tag1.value;
  }
  if (item.type == "approve") {
    tag2.value = !tag2.value;
  }
  if (item.type == "ratePrice") {
    tag3.value = !tag3.value;
  }
  if (item.type == "filters") {
    picker.value.open();
  }
  orderType.value == "desc"
    ? (orderType.value = "asc")
    : (orderType.value = "desc");
  item.type != "filters" ? (types.value = null) : types.value;
  leftList.value = [];
  rightLists.value = [];
  oldleftList.value = [];
  oldrightList.value = [];
  pageNum.value = 1;
  pageSize.value = 10;
  isMore.value = false;
  getProductPage(data);
};

const handleFiltter = (e: any) => {
  pageNum.value = 1;
  //console.log("---筛选---", e, orderType.value);
  let data = {
    screen: true,
  };
  if (orderType.value == "desc") {
    orderType.value = "asc";
  } else {
    orderType.value = "desc";
  }
  getProductPage(data);
  //console.log("---排序---", orderType.value);
};

const headSculpture = computed(() => {
  return userinfo.headSculpture == null || userinfo.headSculpture == ""
    ? "@/static/images/avatar_default.png"
    : userinfo.headSculpture;
});

// 跳转消息
const messageClick = () => {
  if (!uni.getStorageSync("token")) {
    uni.navigateTo({
      url: "/pages/login/login",
    });
    return;
  }
  uni.navigateTo({
    url: `/pagesIndex/message/message`,
  });
};
const goActivities = () => {
  // uni.navigateTo({
  //   url: `/pagesMerchand/activities-info?id=${activitiesId.value}`
  // })
  router(`/pagesMerchand/activities-info?id=${activitiesId.value}`);
};
</script>

<template>
  <navbar :fixed="navbarFixed" :back="false" title="奇石家" />
  <view class="home-container-wrapper" :style="{
    background: `url(${homeBg}) no-repeat`,
    backgroundSize: '750rpx 633rpx',
  }">
    <!-- <view class="header">
      <view class="header-info flex-align-center">
        <view class="head flex flex-center">
          <image :src="headSculpture" class="head-avatar" />
        </view>
        <view class="head-center"></view>
        <view class="right">
          <view class="nologin-title">
            <text v-if="!userStore.state.isLogin" class="" @click="handleLogin"
              >Hello，请登录 ></text
            >
            <text v-else
              >Hello，{{ userinfo.userName ? userinfo.userName : "" }}</text
            >
          </view>
          <view class="location">
            <navigator
              url="/pagesIndex/location/location"
              open-type="navigate"
              hover-class="navigator-hover"
            >
              <image
                class="margin-right-100"
                src="@/static/images/location.png"
              />
              <text>
                {{ cityProvinceStr ? cityProvinceStr : "定位当前地址" }}
              </text>
              <image
                class="margin-left-10"
                src="@/static/images/down-fas.png"
                mode="scaleToFill"
              />
            </navigator>
          </view>
        </view>
      </view>
      <view class="header-chat" @tap="messageClick()">
        <view class="box">
          <uv-badge
            numberType="overflow"
            type="error"
            max="9"
            :value="noReadNumTip"
          ></uv-badge>
        </view>
        <image src="@/static/images/message.png"></image>
      </view>
    </view> -->

    <view class="search" @click="router('/pagesIndex/search/search')">
      <view class="search-icon">
        <!-- <uv-icon name="search" color="#C33E29" width="36rpx" height="36rpx" /> -->
        <image class="" src="@/static/images/search-outline@2x.png" />
      </view>
      <input type="text" placeholder="请输入您想要的奇石" class="search-input" />
    </view>

    <view class="banner">
      <uv-swiper height="368rpx" :radius="12" :list="slideSwiper" keyName="advertsUrl"></uv-swiper>
    </view>
    <!-- 评选活动入口 -->
    <view class="px-activity" @click="goActivities" v-if="activitiesId">
      <image class="" :src="activitiesImage" />
    </view>

    <view class="asdw">
      <view class="grid">
        <view class="nav" @click="handleCollect">
          <image class="" src="@/static/images/collect1.png" />
          <text> 收藏榜 </text>
        </view>
        <view class="nav" @click="handleJewellery('珍宝档案')">
          <image class="" src="@/static/images/shop.png" />
          <text> 珍宝档案 </text>
        </view>
        <view class="nav" @click="handleJewellery('推荐榜')">
          <image class="" src="@/static/images/dianpu.png" />
          <text> 推荐榜 </text>
        </view>
        <view class="nav" @click="handleMarket('认证榜')">
          <image class="" src="@/static/images/renzheng.png" />
          <text> 认证榜 </text>
        </view>
      </view>
      <view class="product-tabs">
        <view class="tab" v-for="(item, index) in userSelectList" :key="index" @click="handleScreen(item, index)">
          <text :class="item.id == userSelectListInd ? 'active' : 'tabtext'">{{
            item.name
            }}</text>
          <view class="margin-top-5 margin-left-10">
            <uv-icon name="arrow-down-fill" size="10" color="#f3604e" v-if="item.id == userSelectListInd"></uv-icon>
            <uv-icon name="arrow-up-fill" size="10" v-else></uv-icon>
          </view>
        </view>
      </view>
      <view class="content">
        <goodsWaterfallIndex :leftList="leftList" :rightLists="rightLists" :searchParams="searchParams"
          :isMore="isMore" />
      </view>
    </view>

    <uv-picker ref="picker" :columns="columns" keyName="deptName" @confirm="confirm"></uv-picker>
    <view class="wrap" ref="backTop">
      <uv-back-top :scroll-top="scrollTop"></uv-back-top>
    </view>
  </view>
  <uv-popup ref="indexPopup" @change="change" bgColor="none" :close-on-click-overlay="false">
    <view class="pop-bg">
      <image src="@/static/images/index_del.png" class="close-pop" @tap="closePop"></image>
      <view class="pop-box">
        <view class="price-pop">
          <text class="num-pop" v-if="
            disccountCounpon &&
            disccountCounpon[counponIndex] &&
            disccountCounpon[counponIndex].couponMoney
          ">{{ disccountCounpon[counponIndex].couponMoney }}</text>
          <text>元</text>
        </view>
        <view class="envelope" v-if="
          disccountCounpon &&
          disccountCounpon[counponIndex] &&
          disccountCounpon[counponIndex].couponName
        ">
          {{ disccountCounpon[counponIndex].couponName }}
        </view>
        <view class="immediate-claim" @tap="receiveClick">
          <image src="@/static/images/index_btn.png"></image>
          <text>立即领取</text>
        </view>
        <view class="remark" v-if="
          disccountCounpon &&
          disccountCounpon[counponIndex] &&
          disccountCounpon[counponIndex].periodValidity
        ">
          领取后{{ disccountCounpon[counponIndex].periodValidity }}内有效
        </view>
      </view>
    </view>
  </uv-popup>
</template>

<style lang="scss" scoped>
.px-activity {
  height: 300rpx;
  border-radius: 20rpx;
  padding: 24rpx;

  image {
    width: 100%;
    height: 100%;
    border-radius: 20rpx;
  }
}

.tabtext {
  color: #000;
}

.active {
  color: red;
}

.bg {
  height: 422rpx;
  width: 100%;
  // background: linear-gradient(to bottom right, #9a2e24, #ffffff);
}

.content {
  margin-bottom: 50px;
  // padding: 0 24rpx;
}

.home-container-wrapper {
  // padding-top: 0;
  // background: url("@/static/images/home-bg.png") no-repeat;
  background-size: 750rpx 633px;
  // position: absolute;
  width: 100%;
  // top: 182rpx;

  .header {
    padding: 20rpx 20rpx;

    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .nologin-title {
      font-size: 40rpx;
      margin-bottom: 10rpx;
      color: #ffffff;
    }

    .header-info {
      display: flex;
      flex-direction: row;

      .head-center {
        width: 20rpx;
        height: 100%;
      }

      .head {
        background-color: #ffffff;
        border-radius: 42rpx;

        width: 100rpx;
        height: 100rpx;
        box-shadow: 3px 3px 1px 0px rgba(0, 0, 0, 0.1);

        .head-avatar {
          border-radius: 42rpx;
          width: 92rpx;
          height: 92rpx;
        }
      }

      .right {
        .location {
          display: flex;
          flex-direction: row;

          image {
            width: 26rpx;
            height: 26rpx;
            //margin-right: 20rpx;
            margin-right: 10rpx;
          }

          text {
            color: #ffffff;

            font-size: 24rpx;
          }
        }
      }
    }

    .header-chat {
      border-radius: 20rpx;
      width: 66rpx;
      height: 66rpx;
      background: rgba(255, 255, 255, 0.5);
      padding: 12rpx;
      position: relative;

      .box {
        // width: 50px;
        // height: 50px;
        position: absolute;
        top: 0;
        right: 0;
        z-index: 1;
      }

      image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .search {
    padding: 26rpx 24rpx 0 24rpx;
    position: relative;

    .search-icon {
      // padding-left: 20rpx;
      position: absolute;
      transform: translate(0, -50%);
      left: 44rpx;
      top: calc(50% + 13rpx);
      width: 36rpx;
      height: 36rpx;

      image {
        width: 36rpx;
        height: 36rpx;
      }
    }

    .search-input {
      background-color: #ffffff;
      padding-left: 64rpx;
      height: 76rpx;
      width: 100%;
      border-radius: 24rpx;
    }
  }

  .banner {
    padding: 0 24rpx;
    margin-top: 26rpx;
    height: 100%;
  }

  .grid {
    display: flex;
    flex-direction: row;
    width: 100%;
    // height: 180rpx;
    background-color: #ffffff;

    justify-content: space-around;
    // margin-bottom: 40rpx;
    // align-items: center;
    padding: 20rpx 0 8rpx 0;
    // border-radius: 24rpx;

    .nav {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      height: 100%;

      image {
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 16rpx;
      }
    }
  }

  .product-tabs {
    margin-top: 32rpx;
    // padding: 0 24rpx;
    // background-color: #ffffff;
    background: linear-gradient(180deg, #fff7f6 0%, #ffffff 100%);
    box-shadow: 0rpx 5rpx 20rpx 0rpx rgba(0, 0, 0, 0.07);
    // background: red;
    border-radius: 24rpx;
    width: 100%;
    height: 110rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-around;

    .tab {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      font-size: 32rpx;

      text {
        // margin-left: 20rpx;
      }

      image {
        margin-top: 20rpx;
      }
    }
  }

  .asdw {
    background: linear-gradient(180deg, #ffffff 0%, #ececec 100%);
    border-radius: 24rpx 24rpx 0rpx 0rpx;
    padding: 0 24rpx;
  }
}

.pop-bg {
  position: reactive;
  width: 92vw;
  height: 70vh;
  background: url("https://leshi-oss.oss-cn-qingdao.aliyuncs.com/047fdc3f-b923-4c32-9be6-c5fd9edff833.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;

  .close-pop {
    position: absolute;
    top: 5vh;
    right: 8vw;
    width: 80rpx;
    height: 80rpx;
  }

  .pop-box {
    position: absolute;
    left: 50%;
    bottom: 160rpx;
    transform: translateX(-50%);
    margin-top: 4vh;
    text-align: center;

    .price-pop {
      text {
        font-style: italic;
        font-weight: 800;
        font-size: 48rpx;
        color: rgb(251, 216, 169);
      }

      .num-pop {
        margin-right: 2rpx;
        font-size: 220rpx;
        text-shadow: 2px 4px 16px rgba(0, 0, 0, 0.3),
          inset 1px 3px 3px rgba(255, 251, 242, 0.5), inset 0px -3px 4px #da703e;
      }
    }

    .envelope {
      color: rgb(251, 216, 169);
      font-size: 48rpx;
      text-shadow: 0px 4px 6px rgba(0, 0, 0, 0.3);
    }

    .immediate-claim {
      position: relative;
      margin-top: 4vh;
      width: 519rpx;
      height: 152rpx;

      image {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 519rpx;
        height: 152rpx;
      }

      text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 10;
        margin-top: -12rpx;
        color: #911c07;
        font-size: 48rpx;
      }
    }

    .remark {
      //margin-top: 1vh;
      font-size: 24rpx;
      color: #ffedbb;
    }
  }
}
</style>
